import axios from 'axios';
import cheerio from 'cheerio';

// 声明此方法用来获取JSONP数据
const news = data => data.data;  // eslint-disable-line no-unused-vars

/**
 * 请求获取新闻数据(注：数据来源央视新闻)
 * @param {Number} page 页码
 */
export async function getNewsList(page = 1) {
    let url = `https://news.cctv.com/2019/07/gaiban/cmsdatainterface/page/news_${page}.jsonp?cb=news`;
    try {
        let resp = await axios.get(url);
        let data = eval(resp.data);
        return {
            newsList: data.list,
            total: data.total,
            page
        };
    } catch (err) {
        // 如果请求报错，则向后台服务器请求数据
        let resp = await axios.get('/api/newslist/' + page);
        return resp.data;
    }
    
}

/**
 * 请求网页链接，提取新闻信息
 * @param {String} url 新闻网页链接
 */
export async function getNewsInfo(type = '', id = '') {
    // 判断参数 type 与 id 为空
    if (type === '' || id === '' || ['photo', 'news'].indexOf(type) === -1) {
        throw new Error('type 或 id 参数为空');
    }
    // 拼接字符串得到新闻详情网页链接
    let date = new Date();
    let y = date.getFullYear();
    let m = (date.getMonth() + 1).toString().padStart(2, '0');
    let d = date.getDate().toString().padStart(2, '0');
    let url = `https://${type}.cctv.com/${y}/${m}/${d}/${id}.shtml`;
    // 初始化默认数据
    let data = { title: '', source: '', pubdate: '', content: '' };
    let resp = null;
    try {
        resp = await axios.get(url);
    } catch (err) {
        // 如果请求报错，则向后台Node服务器请求数据
        resp = await axios.get(`/api/newsinfo/${type}/${id}`);
        return resp.data;
    }
    let $ = cheerio.load(resp.data);
    if (type === 'news') {
        let info = $('#title_area .info').text().split('|');
        data.title = $('#title_area h1').text() || $('.cnt_bd h1').text();
        data.source = info[0] || '来源：' + $('.function .info i a').text();
        data.pubdate = info[1] || $('.function .info i')[0].children[2].data;
        // 删除视频内容
        $('#content_area #myFlash').parent().remove();
        $('#text_area #myFlash').parent().remove();
        data.content = $('#content_area').html() || $('#text_area').html();
    } else {
        data.title = $('.bigTitle').text();
        data.source = '来源：' + $('.tj_top .info i').text().trim();
        data.pubdate = $('.tj_top .info span').text();
        // https://photo.cctv.com/2021/02/10/PHOAwD5cllCiWqHPahxgjsEB210210.xml?randomNum=98
        url = url.replace('shtml', 'xml?randomNum=98');
        resp = await axios.get(url);
        $ = cheerio.load(resp.data);
        data.textList = [];
        data.imageList = [];
        $('li').each((_, el) => {
            data.textList.push(el.children[0].data.replace(/(\[|\]|CDATA)/g, ''));
            data.imageList.push($(el).attr('photourl'));
        });
    }
    return data;
}

// 基础链接
const baseUrl = 'http://api.cms.liulongbin.top/api';

/**
 * 获取图片分类
 */
export async function getPhotoCategoryList() {
    let resp = await axios.get(baseUrl +'/getimgcategory');
    return resp.data.message;
} 

/**
 * 根据图片分类获取图片列表
 * @param {Number} id 
 */
export async function getPhotoListByCategoryId(id = 0) {
    let resp = await axios.get(baseUrl + '/getimages/' + id);
    return resp.data.message; 
}

/**
 * 根据id获取图片信息
 * @param {Number} id 图片id
 */
export async function getPhotoInfo(id) {
    let resp = await axios.get(`${baseUrl}/getimageinfo/${id}`);
    let data = resp.data.message[0]
    // 根据id获取图片信息中的缩略图
    // resp = await axios.get(`${photoAPIUrl}/getthumimages/${id}`);
    // data.thums = resp.data.message;
    data.thums = await getImageList(42879);
    return data;
}

/**
 * 请求获取商品数据
 * @param {Number} page 页码
 */
export async function getGoodsList(page = 1) {
    let resp = await axios.get(baseUrl + '/getgoods?pageindex=' + page);
    return {
        goodsList: resp.data.message,
        page
    };
}

// 获取图片数据
export async function getImageList(id) {
    try {
        let resp = await axios.get(`https://www.mihuashi.com/api/v1/users/${id}/artworks`);
        return resp.data.artworks;
    } catch (err) {
        // 如果请求报错，则向后台Node服务器请求数据
        let resp = await axios.get(`/api/imagelist/${id}`);
        return resp.data;
    }
}

// 获取商品详情
export async function getGoodsInfo(id) {
    let resp = await axios.get(`${baseUrl}/goods/getinfo/${id}`);
    return resp.data.message[0];
}

// 获取购物车列表数据
export async function getShopCartList(ids) {
    if (ids) {
        let resp = await axios.get(`${baseUrl}/goods/getshopcarlist/${ids}`);
        return resp.data.message;
    } else {
        return [];
    }
    
}